#!/usr/bin/env node

const { execSync } = require('child_process')
const fs = require('fs')
const path = require('path')

console.log('🚀 Starting publish process...')

// 检查是否在正确的分支
const currentBranch = execSync('git branch --show-current', { encoding: 'utf8' }).trim()
if (currentBranch !== 'main' && currentBranch !== 'master') {
  console.error('❌ Please publish from main/master branch')
  process.exit(1)
}

// 检查是否有未提交的更改
const status = execSync('git status --porcelain', { encoding: 'utf8' })
if (status.trim()) {
  console.error('❌ Please commit all changes before publishing')
  process.exit(1)
}

// 构建组件库
console.log('📦 Building component library...')
try {
  execSync('npm run build:lib', { stdio: 'inherit' })
} catch (error) {
  console.error('❌ Build failed')
  process.exit(1)
}

// 检查dist目录是否存在
const distPath = path.join(__dirname, '..', 'dist')
if (!fs.existsSync(distPath)) {
  console.error('❌ Dist directory not found')
  process.exit(1)
}

// 运行测试
console.log('🧪 Running tests...')
try {
  execSync('npm run test:run', { stdio: 'inherit' })
} catch (error) {
  console.error('❌ Tests failed')
  process.exit(1)
}

// 发布到npm
console.log('📤 Publishing to npm...')
try {
  execSync('npm publish', { stdio: 'inherit' })
  console.log('✅ Published successfully!')
} catch (error) {
  console.error('❌ Publish failed')
  process.exit(1)
}
